package com.jacksen.demo.view.egl

import android.annotation.TargetApi
import android.graphics.Bitmap
import android.opengl.*
import android.os.Build
import android.view.Surface
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class EGLHelper {

    companion object {
        private val attributes = intArrayOf(
                EGL14.EGL_RED_SIZE, 8, //指定RGB中的R大小（bits）
                EGL14.EGL_GREEN_SIZE, 8, //指定G大小
                EGL14.EGL_BLUE_SIZE, 8, //指定B大小
                EGL14.EGL_ALPHA_SIZE, 8, //指定Alpha大小，以上四项实际上指定了像素格式
                EGL14.EGL_DEPTH_SIZE, 16, //指定深度缓存(Z Buffer)大小
                EGL14.EGL_RENDERABLE_TYPE, 4, //指定渲染api类别, 如上一小节描述，这里或者是硬编码的4(EGL14.EGL_OPENGL_ES2_BIT)
                EGL14.EGL_NONE)  //总是以EGL14.EGL_NONE结尾
    }

    private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
    private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
    private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE

    private var surface: Surface? = null

    private val imageInputRender = ImageInputRender()

    protected val mVertexBuffer: FloatBuffer
    protected val mTextureBuffer: FloatBuffer

    init {
        mVertexBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.CUBE.size * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer()
        mVertexBuffer.put(TextureRotationUtil.CUBE).position(0)
        mTextureBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.TEXTURE_NO_ROTATION.size * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer()
        mTextureBuffer.put(TextureRotationUtil.TEXTURE_NO_ROTATION).position(0)
    }

    fun setSurface(surface: Surface) {
        this.surface = surface
    }

    fun initEgl() {
        imageInputRender.init()

        // 1. 创建与本地窗口系统的连接
        eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
        if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
            // TODO error
        }

        // 2. 初始化 EGl
        val version = IntArray(2)
        val initializeResult = EGL14.eglInitialize(eglDisplay, version, 0, version, 1)
        if (!initializeResult) {
            // TODO error
        }

        // 3. 确定可用的渲染表面配置
        val configs = arrayOfNulls<EGLConfig>(1)
        val numConfig = IntArray(1)
        val result = EGL14.eglChooseConfig(eglDisplay, attributes, 0, configs, 0, configs.size, numConfig, 0)
        if (!result) {
            // TODO error
        }
        val eglConfig = configs[0]

        // 4. 创建 EGLContext
        val contextAttributes = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE)
        eglContext = EGL14.eglCreateContext(eglDisplay, eglConfig, EGL14.EGL_NO_CONTEXT, contextAttributes, 0)

        // 5. 创建渲染表面
        val eglSurfaceAttributes = intArrayOf(EGL14.EGL_NONE)
        eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, eglSurfaceAttributes, 0)

        // 6. 绑定上下文
        val makeCurrentResult = EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
        if (!makeCurrentResult) {
            // TODO error
        }
    }

    fun drawBitmap(bitmap: Bitmap) {
        imageInputRender.onDrawFrame(OpenGLUtils.loadTexture(bitmap, OpenGLUtils.NO_TEXTURE), mVertexBuffer, mTextureBuffer);
        swapBuffers()
    }

    fun swapBuffers() {
        // 7. 交换缓冲
        EGL14.eglSwapBuffers(eglDisplay, eglSurface)
    }

    fun release() {
        EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)
        EGL14.eglDestroyContext(eglDisplay, eglContext)
        EGL14.eglDestroySurface(eglDisplay, eglSurface)
        EGL14.eglReleaseThread()
        EGL14.eglTerminate(eglDisplay)
    }

}